package com.llxwz.controller;


import com.llxwz.entity.Comment;
import com.llxwz.entity.DiscussPost;
import com.llxwz.entity.Event;
import com.llxwz.event.EventProducer;
import com.llxwz.service.CommentService;
import com.llxwz.service.DiscussPostService;
import com.llxwz.util.CommunityConstant;
import com.llxwz.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
public class CommentController implements CommunityConstant {

    @Autowired
    private CommentService commentService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private EventProducer eventProducer;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private DiscussPostService discussPostService;


    @PostMapping("/addComment/{discussPostId}")
    public String addComment(@PathVariable("discussPostId")int discussPostId, Comment comment){
        comment.setUserId(hostHolder.getUser().getId());
        comment.setStatus(0);
        comment.setCreateTime(new Date());
        commentService.addComment(comment);

        //触发评论的事件
        // 触发评论事件
        Map<String,Object> m = new HashMap<>();
        m.put("postId", discussPostId);
        Event event = new Event().builder()
                .exchangeName(EXCHANGE_NAME)
                .queueName(QUEUE_COMMENT)
                .routeName(ROUTE_COMMENT)
                .userId(hostHolder.getUser().getId())
                .entityType(comment.getEntityType())
                .entityId(comment.getEntityId())
                .data(m)
                .build();
        if (comment.getEntityType() == ENTITY_TYPE_POST) {//帖子
            DiscussPost target = discussPostService.findDiscussPostById(comment.getEntityId());
            event.setEntityUserId(target.getUserId());//帖子作者的Id
        } else if (comment.getEntityType() == ENTITY_TYPE_COMMENT) {//评论
            Comment target = commentService.findCommentById(comment.getEntityId());
            event.setEntityUserId(target.getUserId());//评论作者的Id
        }
        eventProducer.fireEvent(event);

        return "redirect:/getPost/"+discussPostId;
    }


}
